package com.taobao.modules.monitor;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CpuTest {

	public static double getCpuUsage() throws Exception {
		double cpuUsed = 0;

		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("top -b -n 1");

		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String str = null;
			String[] strArray = null;

			while ((str = in.readLine()) != null) {
				int m = 0;

				if (str.indexOf(" R ") != -1) {

					strArray = str.split(" ");
					for (String tmp : strArray) {
						if (tmp.trim().length() == 0)
							continue;
						if (++m == 9) {

							cpuUsed += Double.parseDouble(tmp);

						}

					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}
		return cpuUsed;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			for(int i =0; i < 100 ; i++ ){
				Thread.sleep(1000);
				System.out.println(CpuTest.getCpuUsage() * 10);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
